package dnl.persistence.orm;

import org.apache.commons.lang.StringUtils;

import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author daniel
 *
 */
public class JpqlQueryBuilder extends QueryBuilder {

	protected Class<?> selectedEntity;
    protected List<String> paramNames;

	public JpqlQueryBuilder() {
	}

	public JpqlQueryBuilder(Class<?> selectedEntity) {
		this.selectedEntity = selectedEntity;
	}

    @Override
    public QueryBuilder where(String condition, Object... values) {
        resolveParamNames(condition);
        return super.where(condition, values);
    }

    @Override
    public QueryBuilder and(String condition, Object... values) {
        resolveParamNames(condition);
        return super.and(condition, values);
    }

    @Override
    public QueryBuilder or(String condition, Object... values) {
        resolveParamNames(condition);
        return super.or(condition, values);
    }

    private void resolveParamNames(String condition) {
        final String[] splits = StringUtils.split(condition, " ,.=+-()*%^$&#@!");
        for (int i = 0; i < splits.length; i++) {
            if(splits[i].startsWith(":")){
                addParamName(splits[i].substring(1));
            }
        }
    }

    protected void addParamName(String paramName){
        if(paramNames == null){
            paramNames = new ArrayList<>();
        }
        paramNames.add(paramName);
    }

    public void fillQueryParameters(Query query) {
		Object[] queryParams = getQueryParams();
		for (int i = 0; i < queryParams.length; i++) {
            if (paramNames!= null){
                query.setParameter(paramNames.get(i), queryParams[i]);
            }
            else {
                query.setParameter(i + 1, queryParams[i]);
            }
		}
	}
}
